import os
from flask import Flask
from .extensions import db, cors  # 使用相对导入，添加点号
import pymysql
from flask_cors import CORS
from flask_jwt_extended import JWTManager

# 注册 PyMySQL 作为 MySQLdb
pymysql.install_as_MySQLdb()

def create_app(config_file='config.py'):
    app = Flask(__name__)

    # 启用CORS
    CORS(app, supports_credentials=True, resources={
        r"/api/*": {
            "origins": ["http://localhost:5173"],
            "methods": ["GET", "POST", "OPTIONS"],
            "allow_headers": ["Content-Type", "Authorization"]
        }
    })
    # 获取配置文件的绝对路径
    config_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', config_file))

    # 检查配置文件是否存在
    if not os.path.exists(config_path):
        raise FileNotFoundError(f'配置文件不存在: {config_path}')

    # 加载配置
    app.config.from_pyfile(config_path)

    # 初始化扩展
    db.init_app(app)
    cors.init_app(app, supports_credentials=True)
    JWTManager(app)

    # 注册路由
    from .auth_routes import init_auth_routes
    from .main_routes import init_main_routes
    from .profile_routes import init_profile_routes
    from .photo_upload_routes import init_photo_upload_routes

    init_auth_routes(app)
    init_main_routes(app)
    init_profile_routes(app)
    init_photo_upload_routes(app)

    return app